//
//  M4Image.swift
//  M4
//
//  Created by YuChuang on 2024/8/13.
//

import Foundation
import UIKit
import CoreMedia
import SDWebImage

class M4Image {
    
    static func M4SampleBuffer(sbuffer:CMSampleBuffer?, orientation: UIImage.Orientation) -> UIImage? {
        guard sbuffer != nil && CMSampleBufferIsValid(sbuffer!) == true else { return nil }
        let pixBuffer = CMSampleBufferGetImageBuffer(sbuffer!)
        let ciimage = CIImage(cvPixelBuffer: pixBuffer!)
        return UIImage(ciImage: ciimage, scale: 1.0, orientation: orientation)
    }
    
    static func M4ImageCropped(originImg:UIImage, croppedView: UIView) -> UIImage? {
        croppedView.layoutIfNeeded()
        let w = croppedView.bounds.size.width
        let h = croppedView.bounds.size.height
        let scale = UIScreen.main.scale
        let size = CGSize(width: w * scale, height: h * scale)
        let scaledImg = originImg.sd_resizedImage(with: size, scaleMode: .aspectFill)
        let cropFrame = CGRectMake(((scaledImg?.size.width)! - size.width) * 0.5,
                                   ((scaledImg?.size.height)! - size.height) * 0.5, size.width, size.height)
        let finalImage = scaledImg?.sd_croppedImage(with: cropFrame)
        return finalImage
    }
    
    func compressImageToBase64Async(_ image: UIImage, maxFileSizeKB: Int = 300, completion: @escaping (String?) -> Void) {
        DispatchQueue.global(qos: .userInitiated).async {
            let maxSize = maxFileSizeKB * 1024
            var compression: CGFloat = 1.0
            var imageData = image.jpegData(compressionQuality: compression)

            // 不断压缩，直到符合大小或质量到最低
            while let data = imageData, data.count > maxSize, compression > 0.1 {
                compression -= 0.1
                imageData = image.jpegData(compressionQuality: compression)
            }

            guard let finalData = imageData else {
                DispatchQueue.main.async {
                    completion(nil)
                }
                return
            }

            let base64String = finalData.base64EncodedString()

            DispatchQueue.main.async {
                completion(base64String)
            }
        }
    }
    
    
    
    
    static func M4ImageCompress(image: UIImage, maxSize: Int) -> Data? {
        var compress: CGFloat = 1.0
        var imgData = image.jpegData(compressionQuality: compress)
        
        while let data = imgData, data.count > maxSize && compress > 0 {
            compress -= 0.1
            imgData = image.jpegData(compressionQuality: compress)
        }
        
        return imgData
    }

    // 使用URLSession下载图片
    static func downloadImage(from url: URL, completion: @escaping (UIImage?) -> Void) {
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data, error == nil, let image = UIImage(data: data) else {
                completion(nil)
                return
            }
            completion(image)
        }.resume()
    }

    
}
